<template>
  <div class="app-container">
    <el-form ref="form" inline :model="form" class="form-options" label-width="100px">
      <el-form-item label="角色名称">
        <el-autocomplete
          ref="roleNameRef"
          v-model="form.roleName"
          placeholder="请输入角色名称"
          :fetch-suggestions="querySearchRole"
          :trigger-on-focus="false"
          clearable
          @select="handleSelectRole"
          @clear="clickClearroleNameRef"/>
      </el-form-item>
      <div class="btns">
        <el-button type="primary" v-permission="['sys_manage_role_quer']" @click="onQuery">查询</el-button>
        <el-button type="primary" v-permission="['sys_manage_role_add']" @click="onAdd">新建</el-button>
        <el-button type="danger" v-permission="['sys_manage_role_del']" @click="onDelete">删除</el-button>
      </div>
    </el-form>
    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      header-cell-class-name="table-header"
      style="width: 100%;margin-top: 20px">
      <el-table-column
        type="selection"
        width="50">
      </el-table-column>
      <el-table-column
        label="序号"
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色名称">
      </el-table-column>
      <el-table-column
        prop="description"
        label="角色描述"
    
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope='scope'>
          <el-button type="primary" v-permission="['sys_manage_role_edit']" @click="handleOperateClick(scope.row,'编辑')">
            编辑
          </el-button>
          <el-button type="danger" v-permission="['sys_manage_role_del']" @click="handleOperateClick(scope.row,'删除')">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right;margin-top: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <el-dialog
      center
      :title="dialogTitle"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="420px">
      <el-form ref="ruleForm" :model="dataForm" :rules="$rules.roleRules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName" v-if="dialogTitle=='新增角色'">
          <el-input v-model="dataForm.roleName" style="width: 250px" placeholder="请输入角色名称" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName2" v-else>
          <el-input v-model="dataForm.roleName2" style="width: 250px" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <!--        <el-form-item label="角色权限" prop="moduleInfoList">-->
        <!--          <el-cascader-->
        <!--            style="width: 250px"-->
        <!--            ref="roleTree"-->
        <!--            :options="dataForm.permissionTree"-->
        <!--            v-model="dataForm.moduleInfoList"-->
        <!--            :show-all-levels="false"-->
        <!--            :props="props"-->
        <!--            clearable-->
        <!--            collapse-tags></el-cascader>-->
        <!--        </el-form-item>-->
        <el-form-item label="角色权限">
          <el-cascader
            style="width: 250px"
            ref="roleTree"
            :options="dataForm.permissionTree"
            v-model="dataForm.moduleInfoList"
            :show-all-levels="false"
            :props="props"
            clearable
            collapse-tags></el-cascader>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            type="textarea"
            style="width: 250px"
            :rows="2"
            v-model="dataForm.description"
            placeholder="请输入角色描述" maxlength="120"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" v-if="dialogTitle == '新增角色'" @click="saveData()">保存</el-button>
        <el-button type="primary" v-else @click="editData()">保存</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, deleteRole, getPermissionTree, updateRole, addRole } from '@/api/user'
import { transfromTreeData } from '@/utils/public'

export default {
  name: 'RoleManage',
  data() {
    return {
      currentPage: 1,
      total: 0,
      pageSize: 10,
      form: {
        roleName: ''
      },
      props: { multiple: true, value: 'id', label: 'moduleName' },
      tableData: [],
      multipleSelection: [],
      dataForm: {},
      dialogTitle: '新增角色',
      dialogVisible: false
    }
  },
  created() {
    this.onQuery()
  },
  methods: {
    handleSizeChange: function(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getTableData()
    },
    handleCurrentChange: function(val) {
      this.currentPage = val
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleOperateClick(row, tag) {
      if (tag == '删除') {
        this.$confirm('确认删除此条数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.handleDelete([{ id: row.id }])
        })
      } else {
        getPermissionTree({ roleId: row.id }).then(res => {
          const moduleInfoList = []
          const subList = []
          // 将选中的tree节点转成[[9,3,1],[9,3,1],[9,3,1]]
          transfromTreeData(res.resultData, subList, moduleInfoList)
          this.dataForm = {
            id: row.id,
            roleName: row.roleName,
            roleName2: row.roleName,
            description: row.description,
            moduleInfoList: moduleInfoList,
            permissionTree: res.resultData
          }
          this.dialogVisible = true
          this.dialogTitle = '编辑角色'
        })
      }
    },
    /**
     * 模糊查询角色
     * @param queryString
     * @param cb
     */
    querySearchRole: function(queryString, cb) {
      // 调用 callback 返回建议列表的数据
      const results = []
      cb(results)
    },
    /**
     * 选择角色
     * @param item
     */
    handleSelectRole(item) {
      console.log(item)
    },
    clickClearroleNameRef(){
      this.$nextTick(() => {
        if (this.$refs.roleNameRef) {
          this.$refs.roleNameRef.activated = true;
        }
      });
    },
    getTableData() {
      const param = { page: this.currentPage, rows: this.pageSize }
      Object.assign(param, this.form)
      getRoles(param).then(res => {
        this.tableData = res.resultData
        this.total = res.total
        this.multipleSelection = []
      })
    },
    handleDelete(ids) {
      deleteRole(ids).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.tableData = []
        this.getTableData()
      })
    },
    saveData() {
      const _this = this
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const ids = []
          _this.dataForm.moduleInfoList.forEach(item => {
            ids.push.apply(ids, item)
          })
          const moduleInfoList = []
          ids.forEach(id => {
            moduleInfoList.push({ id: id })
          })
          const param = {
            roleName: _this.dataForm.roleName,
            description: _this.dataForm.description,
            moduleInfoList: moduleInfoList
          }
          addRole(param).then(response => {
            if (response.success) {
              _this.$message({
                message: '新增成功',
                type: 'success'
              })
              _this.dialogVisible = false
              _this.onQuery()
            }
          })
        } else {
          return false
        }
      })
    },
    editData() {
      const _this = this
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const ids = []
          _this.dataForm.moduleInfoList.forEach(item => {
            ids.push.apply(ids, item)
          })
          const moduleInfoList = []
          ids.forEach(id => {
            moduleInfoList.push({ id: id })
          })

          const param = {
            id: _this.dataForm.id,
            roleName: _this.dataForm.roleName2,
            description: _this.dataForm.description,
            moduleInfoList: moduleInfoList
          }
          updateRole(param).then(response => {
            if (response.success) {
              _this.$message({
                message: '更新成功',
                type: 'success'
              })
              _this.dialogVisible = false
              _this.getTableData()
            }
          })
        } else {
          return false
        }
      })
    },
    onQuery() {
      this.currentPage = 1
      this.getTableData()
    },
    onDelete() {
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      const ids = []
      this.multipleSelection.forEach(item => {
        ids.push({ id: item.id })
      })
      this.$confirm('确认删除选中的数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.handleDelete(ids)
      })
    },
    onAdd() {
      getPermissionTree({}).then(res => {
        this.dataForm = {
          name: '',
          description: '',
          moduleInfoList: [],
          permissionTree: res.resultData
        }
        this.dialogVisible = true
        this.dialogTitle = '新增角色'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}
</style>

